package com.example.myproject.controller;

import com.example.myproject.model.Contract;
import com.example.myproject.model.CustomUserDetails;
import com.example.myproject.repository.ContractRepository;
import com.example.myproject.service.ContractService;
import com.example.myproject.service.FileStorageService;
import com.example.myproject.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/contract")
public class ContractController {

    @Autowired
    private ContractService contractService;

    @Autowired
    private ContractRepository contractRepository;

    @Autowired
    private FileStorageService fileStorageService;


    private boolean checkPermission(Long contractId, int requiredStatus, UserDetails userDetails) {
        if (!(userDetails instanceof CustomUserDetails)) {
            return false;
        }
        CustomUserDetails customUserDetails = (CustomUserDetails) userDetails;
        Map<Long, List<String>> contractRoles = customUserDetails.getContractRoles();

        // 首先检查用户是否对该合同ID有任何角色权限
        List<String> roles = contractRoles.get(contractId);
        if (roles == null) {
            return false; // 没有对这个合同的任何权限
        }

        // 然后根据合同状态检查具体的角色权限
        switch (requiredStatus) {
            case 1: // 会签状态
                return roles.contains("countersign");
            case 3: // 定稿状态
                return roles.contains("Finalize");
            case 5: // 审批状态
                return roles.contains("approval");
            case 7: // 签订状态
                return roles.contains("signing");
            default:
                return false;
        }
    }




    // 上传文件
    @PostMapping("/upload")
    public ResponseEntity<Result> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(Result.fileStorageError("上传文件不能为空"));
        }

        String fileUrl = fileStorageService.storeFile(file);
        if (fileUrl == null || fileUrl.isEmpty()) {
            return ResponseEntity.badRequest().body(Result.fileStorageError("文件存储失败"));
        }
        return ResponseEntity.ok(Result.success(fileUrl, "文件上传成功"));
    }

    //起草合同
    @PostMapping("/draft")
    public ResponseEntity<Result> draftContract(@RequestBody Contract contract, Authentication authentication) {
        if (contract == null || contract.getName() == null || contract.getCustomer() == null ||
                contract.getBeginTime() == null || contract.getEndTime() == null || contract.getContent() == null) {
            return ResponseEntity.badRequest().body(Result.error("400", "合同信息不完整，请检查必填项是否填写"));
        }

        String username = ((UserDetails) authentication.getPrincipal()).getUsername();
        Contract savedContract = contractService.draft(contract, username);

        if (savedContract == null) {
            return ResponseEntity.badRequest().body(Result.error("500", "合同保存失败"));
        }
        return ResponseEntity.ok(Result.success(savedContract, "合同起草成功"));
    }

    //查找所有合同
    @GetMapping
    public Result<List<Contract>> getAllContracts() {
        List<Contract> contracts = contractService.getAllContracts();
        return Result.success(contracts, "查找所有合同成功！");
    }


    //查找合同
    @GetMapping("/query")
    public Result<List<Contract>> searchContractsByName(@RequestParam(required = false) String name) {
        if (name == null || name.isEmpty()) {
            // 如果接收内容为空，则调用已经存在的查找所有合同的方法
            return getAllContracts();
        } else {
            List<Contract> contracts = contractService.searchContractsByName(name);
            if (!contracts.isEmpty()) {
                return Result.success(contracts, "根据合同名搜索合同成功！");
            } else {
                return Result.error("404", "没有找到符合条件的合同！");
            }
        }
    }

    //获取合同详情
    @GetMapping("/name/{contractName}")
    public ResponseEntity<Result<Contract>> getContractDetailsByName(@PathVariable String contractName) {
        Optional<Contract> contract = contractService.getContractDetailsByName(contractName);
        if (contract.isPresent()) {
            return ResponseEntity.ok(Result.success(contract.get(), "获取合同详情成功！"));
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Result.error("404", "未找到指定名称的合同！"));
        }
    }


    //会签


    // 获取所有待会签的合同列表
    @GetMapping("/listCounterSignContract")
    public Result<List<Contract>> listCounterSignContracts(Authentication authentication) {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        List<Contract> contracts = contractService.findContractsByStatus(1);
        contracts = contracts.stream()
                .filter(contract -> checkPermission(contract.getId(), contract.getStatus(), userDetails))
                .collect(Collectors.toList());
        return contracts.isEmpty() ? Result.error("404", "当前没有待会签的合同") : Result.success(contracts, "获取待会签合同列表成功");
    }


    // 根据合同名称查询待会签的合同
    @GetMapping("/counterSigneContracts/query")
    public Result<List<Contract>> queryCounterSignContractsByName(@RequestParam String name, Authentication authentication) {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        List<Contract> contracts = contractService.searchContractsByNameAndStatus(name, 1);
        contracts = contracts.stream()
                .filter(contract -> checkPermission(contract.getId(), contract.getStatus(), userDetails))
                .collect(Collectors.toList());
        return contracts.isEmpty() ? Result.error("404", "没有找到符合条件的待会签合同") : Result.success(contracts, "根据合同名搜索待会签合同成功");
    }



    // 提交会签意见
    @PostMapping("/countersign/{contractName}")
    public ResponseEntity<?> submitCounterSign(@PathVariable String contractName, @RequestBody CounterSignRequest counterSignRequest, Authentication authentication) {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        Long contractId = contractService.getContractIdByName(contractName);
        if (!checkPermission(contractId, 1, userDetails)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        try {
            Contract contract = contractService.updateCounterSignOpinion(contractName, counterSignRequest.getOpinion());
            if (contract != null) {
                return ResponseEntity.ok(Result.success("会签意见提交成功"));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Result.error("404", "未找到指定的合同"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error("500", "服务器错误：" + e.getMessage()));
        }
    }


    //定稿

    // 获取所有待定稿的合同列表
    @GetMapping("/listFinalizeContract")
    public Result<List<Contract>> listFinalizeContracts(Authentication authentication) {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        List<Contract> contracts = contractService.findContractsByStatus(3);
        List<Contract> filteredContracts = contracts.stream()
                .filter(contract -> checkPermission(contract.getId(), 3, userDetails))
                .collect(Collectors.toList());
        return Result.success(filteredContracts, "获取待定稿合同列表成功");
    }

    // 根据合同名称查询待定稿的合同
    @GetMapping("/listFinalizeContract/query")
    public Result<List<Contract>> queryFinalizeContractsByName(@RequestParam String name, Authentication authentication) {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        List<Contract> contracts = contractService.searchContractsByNameAndStatus(name, 3);
        List<Contract> filteredContracts = contracts.stream()
                .filter(contract -> checkPermission(contract.getId(), 3, userDetails))
                .collect(Collectors.toList());
        return filteredContracts.isEmpty() ? Result.error("404", "没有找到符合条件的待定稿合同") : Result.success(filteredContracts, "根据合同名搜索待定稿合同成功");
    }


    // 定稿合同内容
    @PostMapping("/name/{contractName}/finalize")
    public ResponseEntity<?> finalizeContract(@PathVariable String contractName, @RequestBody ContractContent contractContent, Authentication authentication) {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        Long contractId = contractService.getContractIdByName(contractName);
        if (!checkPermission(contractId, 3, userDetails)) {  // 注意这里的状态代码与具体场景相符
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        try {
            Contract contract = contractService.finalizeContract(contractName, contractContent.getContent());
            if (contract != null) {
                return ResponseEntity.ok(Result.success("合同定稿成功"));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Result.error("404", "未找到指定的合同"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error("500", "服务器错误：" + e.getMessage()));
        }
    }



    //审批

    // 获取所有待审批的合同列表

    @GetMapping("/pending_approval")
    public Result<List<Contract>> listApproveContracts(Authentication authentication) {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        List<Contract> contracts = contractService.findContractsByStatus(5);
        List<Contract> filteredContracts = contracts.stream()
                .filter(contract -> checkPermission(contract.getId(), 5, userDetails))
                .collect(Collectors.toList());
        return Result.success(filteredContracts, "获取待审批合同列表成功");
    }

    // 根据合同名称查询待审批的合同
    @GetMapping("/pending_approval/query")
    public Result<List<Contract>> queryApproveContractsByName(@RequestParam String name, Authentication authentication) {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        List<Contract> contracts = contractService.searchContractsByNameAndStatus(name, 5);
        List<Contract> filteredContracts = contracts.stream()
                .filter(contract -> checkPermission(contract.getId(), 5, userDetails))
                .collect(Collectors.toList());
        return filteredContracts.isEmpty() ? Result.error("404", "没有找到符合条件的待审批合同") : Result.success(filteredContracts, "根据合同名搜索待审批合同成功");
    }


    // 审批合同
    @PostMapping("/name/{contractName}/approve")
    public ResponseEntity<?> approveContract(@PathVariable String contractName, @RequestBody ApprovalRequest approvalRequest, Authentication authentication) {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        Long contractId = contractService.getContractIdByName(contractName);
        if (!checkPermission(contractId, 5, userDetails)) {  // 注意这里的状态代码与具体场景相符
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        try {
            Contract contract = contractService.approveContract(contractName, approvalRequest.getOpinion(), approvalRequest.getStatus());
            if (contract != null) {
                return ResponseEntity.ok(Result.success("合同审批成功"));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Result.error("404", "合同审批失败：未找到指定的合同"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error("500", "服务器错误：" + e.getMessage()));
        }
    }



    //签订
    // 获取所有待签订的合同列表
    @GetMapping("/pending")
    public Result<List<Contract>> listPendingContracts() {
        List<Contract> contracts = contractService.findContractsByStatus(7);
        if (!contracts.isEmpty()) {
            return Result.success(contracts, "获取待签订合同列表成功");
        } else {
            return Result.error("404", "当前没有待签订的合同");
        }
    }


    @GetMapping("/pending/query")
    public Result<List<Contract>> queryPendingContractsByName(@RequestParam String name) {
        List<Contract> contracts = contractService.searchContractsByNameAndStatus(name, 7);
        if (!contracts.isEmpty()) {
            return Result.success(contracts, "根据合同名搜索待签订合同成功");
        } else {
            return Result.error("404", "没有找到符合条件的待签订合同");
        }
    }

    // 处理合同签订
    @PostMapping("/{contractName}/sign")
    public ResponseEntity<?> signContract(@PathVariable String contractName, @RequestBody SignInfoRequest signInfoRequest, Authentication authentication) {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        Long contractId = contractService.getContractIdByName(contractName);
        if (!checkPermission(contractId, 7, userDetails)) {  // 注意这里的状态代码与具体场景相符
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        try {
            Contract contract = contractService.updateSignOpinion(contractName, signInfoRequest.getSignInfo());
            if (contract != null) {
                return ResponseEntity.ok(Result.success("合同签订成功"));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Result.error("404", "未找到指定的合同"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error("500", "服务器错误：" + e.getMessage()));
        }
    }

    //分配：
    // 分配合同给指定的会签人、审批人和签订人
    @PostMapping("/{contractName}/assign")
    public ResponseEntity<String> assignContract(@PathVariable String contractName, @RequestBody AssignmentRequest assignmentRequest) {
        try {
            contractService.assignContractByName(contractName, assignmentRequest.getCountersignUsers(), assignmentRequest.getApprovalUsers(), assignmentRequest.getSigningUsers());
            return ResponseEntity.ok("合同分配成功！");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("合同分配失败：" + e.getMessage());
        }
    }
    @GetMapping("/drafting")
    public ResponseEntity<Result<List<Contract>>> listDraftingContracts() {
        List<Contract> contracts = contractService.findContractsByStatus(10); // 待分配是10
        if (contracts.isEmpty()) {
            return ResponseEntity.ok(Result.error("404", "当前没有待分配的合同"));
        } else {
            return ResponseEntity.ok(Result.success(contracts, "获取待分配合同列表成功"));
        }
    }


    static class ContractContent {
        private String content;
        public String getContent() {
            return content;
        }
        public void setContent(String content) {
            this.content = content;
        }
    }

    static class CounterSignRequest {
        private String opinion;
        public String getOpinion() {
            return opinion;
        }
        public void setOpinion(String opinion) {
            this.opinion = opinion;
        }
    }

    static class ApprovalRequest {
        private String opinion;
        private String status;
        public String getOpinion() {
            return opinion;
        }
        public void setOpinion(String opinion) {
            this.opinion = opinion;
        }
        public String getStatus() {
            return status;
        }
        public void setStatus(String status) {
            this.status = status;
        }
    }

    static class SignInfoRequest {
        private String signInfo;
        public String getSignInfo() {
            return signInfo;
        }
        public void setSignInfo(String signInfo) {
            this.signInfo = signInfo;
        }
    }

    static class AssignmentRequest {
        private List<Long> countersignUsers;
        private List<Long> approvalUsers;
        private List<Long> signingUsers;
        public List<Long> getCountersignUsers() {
            return countersignUsers;
        }
        public void setCountersignUsers(List<Long> countersignUsers) {
            this.countersignUsers = countersignUsers;
        }
        public List<Long> getApprovalUsers() {
            return approvalUsers;
        }
        public void setApprovalUsers(List<Long> approvalUsers) {
            this.approvalUsers = approvalUsers;
        }
        public List<Long> getSigningUsers() {
            return signingUsers;
        }
        public void setSigningUsers(List<Long> signingUsers) {
            this.signingUsers = signingUsers;
        }
    }
}
